package com.issac.vhr.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.issac.vhr.entity.RespBean;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/*
*  验证码校验
*
* */
@Component
public class VerifyCodeFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //判断是否验证码接口 不是放行
        if ("POST".equals(req.getMethod()) && "/doLogin".equals(req.getServletPath())){
            //登录请求
            String code = req.getParameter("code");
            String index_code = (String) req.getSession().getAttribute("verify_code");
            if (code == null || "".equals(code) || !index_code.toLowerCase().equals(code.toLowerCase())){
                //验证码不正确
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter writer = resp.getWriter();
                RespBean respBean = RespBean.error("验证码不正确");
                writer.write(new ObjectMapper().writeValueAsString(respBean));
                writer.flush();
                writer.close();
                return;
            }else {
                filterChain.doFilter(req,resp);
            }
        }else {
            filterChain.doFilter(req,resp);
        }


    }
}
